package com.prs.crm.action.stock;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.action.FlowAction;
import com.prs.crm.annotation.Clew;
import com.prs.crm.annotation.FlowActive;
import com.prs.crm.annotation.FlowStart;
import com.prs.crm.domain.purchase.PurchaseOrder;
import com.prs.crm.domain.purchase.PurchaseOrderDetail;
import com.prs.crm.domain.purchase.PurchaseStoreIn;
import com.prs.crm.domain.stock.Product;
import com.prs.crm.domain.store.StoreIn;
import com.prs.crm.domain.store.StoreInDetail;
import com.prs.crm.domain.store.StoreRoom;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeInvoice;
import com.prs.crm.service.purchase.PurchaseOrderDetailService;
import com.prs.crm.service.purchase.PurchaseOrderService;
import com.prs.crm.service.stock.ProductService;
import com.prs.crm.service.stock.ProductStoreService;
import com.prs.crm.service.stock.PurchaseService;
import com.prs.crm.service.stock.StockAlertService;
import com.prs.crm.service.stock.StoreInService;
import com.prs.crm.service.stock.StoreRoomService;
import com.prs.crm.service.sys.CodeInvoiceService;
import com.prs.crm.service.sys.CodeService;

public class StoreInAction extends FlowAction<StoreIn> {

	private static final long serialVersionUID = 1L;

	private StoreIn storein;
	private String Encode;
	private CodeInvoice codeInvoice;
	private CodeInvoiceService codeInvoiceService;
	private Code code;
	private CodeService codeService;
	private Collection<CodeInvoice> codelist;
	private String[] names;
	private Product[] products;
	private String[] products1;
	private String[] storenumsStrings;
	private Integer[] storeinNums;
	private Integer[] detailid;
	private Integer[] detailstoreNum;
	private String orderOrproduct;
    private String[] isorder;
	private Collection<StoreInDetail> slist;

	@Autowired
	private ProductService productService;

	@Autowired
	private PurchaseService purchaseService;
	@Autowired
	private StoreInService storeInService;
	@Autowired
	private StoreRoomService storeRoomService;
	@Autowired
	private ProductStoreService productstoreService;

	private List<StoreRoom> storerooms;

	private List<Product> productlist;

	private PaginationSupport pagination;
	private List<String> mapValidateStockAlert;
	private Map<String, Double> mapValidateInMap;
	private StockAlertService stockAlertService;
	private StoreRoom storeRoom;
	private PurchaseOrderDetailService purchaseOrderDetailService;
	private PurchaseOrderService purchaseOrderService;
	private String flow;

	@FlowActive(target = "storein", flowservice = "storeInService")
	@Action("editStoreIn")
	public String editStoreIn() {
		this.codelist = this.getCodeInvoiceService().getInvoiceCodeType("入库单");
		this.storerooms = this.storeRoomService.getAllstoreroom();
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@FlowStart(flowservice = "storeInService", target = "storein")
	@Action(value = "saveStoreIn", results = {
			@Result(name = "success", type = "redirect", location = "listStoreIn"),
			@Result(name = "error", type = "chain", location = "editStoreIn"),
			@Result(name = "none", type = "redirect", location = "listStoreIn") })
	public String saveStoreIn() {
		
		if ("x".equals(Encode) || "".equals(Encode)) {
			this.addActionError("请选择编码类型");
			return ERROR;
		}
		if (storein.getStoreInCode() == null
				|| "".equals(storein.getStoreInCode().trim())) {
			this.addActionError("编码不能为空");
			return ERROR;
		}
		if ("n".equals(Encode)) {
			int EncodeRplice = this.getCodeService().getBackRpliceAll("手动编码",
					"库房入库", storein.getStoreInCode());
			if (EncodeRplice != 0) {
				this.addActionError("编码重复!请重新输入");
				return ERROR;
			}
		}
		if (flow == null || flow.equals("")) {
			this.addActionError("审核流程不能为空");
			return ERROR;
		}
		if (storein.getBatchNum() == null || storein.getBatchNum().equals("")) {
			this.addActionError("批号不能为空");
			return ERROR;
		}
		if (storein.getStoragedata() == null) {
			this.addActionError("时间不能为空");
			return ERROR;
		}
		if (storein.getRoom() == null) {
			this.addActionError("仓库不能为空");
			return ERROR;
		}
		if (products == null) {
			this.addActionError("入库明细不能为空");
			return ERROR;
		}
		if (storein.getTitlename() == null || storein.getTitlename().equals("")) {
			this.addActionError("入库主题不能为空");
			return ERROR;
		}
		if ("n".equals(Encode)) {
			Code codes = new Code();
			codes.setCodeValue(storein.getStoreInCode());
			codes.setEntityName(this.getClass().getName());
			codes.setCodeType("手动编码");
			codes.setCodeMolde("库房入库");
			this.getCodeService().save(codes);
			storein.setCode(codes);
		} else {
			CodeInvoice Vob = this.getCodeInvoiceService().getVobject(
					codeInvoice.getId());
			Code codes = new Code();
			codes.setEntityName(this.getClass().getName());
			codes.setCodeValue(storein.getStoreInCode());
			Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
			this.getCodeInvoiceService().saveOrUpdate(Vob);
			codes.setCodeType(Vob.getCodePlan());
			codes.setCodeMolde("库房入库");
			this.getCodeService().save(codes);
			storein.setCode(codes);
		}
          
		if ("B".equals(orderOrproduct)) {
			boolean inOver = true;
			PurchaseOrder purchaseOrder = ((PurchaseOrderDetail) this
					.getPurchaseOrderDetailService().get(detailid[0]))
					.getPurchaseOrder();
			storein.setPurchaseOrderId(purchaseOrder.getId());
			for (int i = 0; i < detailid.length; i++) {
				PurchaseOrderDetail detail = (PurchaseOrderDetail) this
						.getPurchaseOrderDetailService().get(detailid[i]);

				detail.setInNum(storeinNums[i] + detail.getInNum());
				if (detail.getStockNum() == detail.getInNum()) {
					detail.setInType(1);
				} else {
					inOver = false;
				}
				this.getPurchaseOrderDetailService().save(detail);
				// this.getPurchaseService().getDetail(detailid[i]).setStoredNum(storeinNums[i]);
				// this.getPurchaseService().saveDetail(this.getPurchaseService().getDetail(detailid[i]));
				// this.getPurchaseService().getDetail(detailid[i]).setStockNum(this.getPurchaseService().getDetail(detailid[i]).getMaxStoreNum());
				// this.getPurchaseService().saveDetail(this.getPurchaseService().getDetail(detailid[i]));

			}
			
			
			if (inOver) {
				purchaseOrder.setPurStoreState(2);
			}

		}
		if(isorder!=null){
			storein.setFlowstatus(2);
		}
		this.storeInService.save(storein, storeinNums, names, products);
		this.setPrompt("操作成功");
		/**
		 * 编码产生
		 */

		return SUCCESS;

	}

	@Action(value = "validateStockAlert1", results = { @Result(name = "success", type = "json", params = {
			"root", "mapValidateStockAlert" }) })
	public String validateStockAlert1() {
		if (getProducts(products1) == null
				|| getNumbers(storenumsStrings) == null) {
			mapValidateStockAlert = null;
		} else {
			try {
				mapValidateStockAlert = this.getStockAlertService()
						.validateStockAlert(storeRoom, getProducts(products1));
				products1 = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}

	@Action(value = "validateIn", results = { @Result(name = "success", type = "json", params = {
			"root", "mapValidateInMap" }) })
	public String validateIn() {
		// getProducts(products1);
		// System.out.println("validateIn");
		// System.out.println(storeRoom.getName() + "     " + products.length);
		if (getProducts(products1) == null
				|| getNumbers(storenumsStrings) == null) {
			mapValidateInMap = null;
		} else {
			try {
				mapValidateInMap = this.getStockAlertService().validateInStore(
						storeRoom, getProducts(products1),
						getNumbers(storenumsStrings),
						this.getProductstoreService());

			} catch (Exception e) {
				e.printStackTrace();
			}
			products1 = null;
			storenumsStrings = null;
		}
		return SUCCESS;
	}

	@Action("listStoreIn")
	public String excute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				StoreIn.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getStoreInService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("viewStoreIn")
	public String viewStoreIn() {
		storein = this.getStoreInService().get(storein.getId());
		this.slist = storein.getDetails();
		this.displayEndNodes(storein);
		return SUCCESS;
	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

	public StoreIn getStorein() {
		return storein;
	}

	public void setStorein(StoreIn storein) {
		this.storein = storein;
	}

	public StoreInService getStoreInService() {
		return storeInService;
	}

	public void setStoreInService(StoreInService storeInService) {
		this.storeInService = storeInService;
	}

	public List<StoreRoom> getStorerooms() {
		return storerooms;
	}

	public void setStorerooms(List<StoreRoom> storerooms) {
		this.storerooms = storerooms;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public StoreRoomService getStoreRoomService() {
		return storeRoomService;
	}

	public void setStoreRoomService(StoreRoomService storeRoomService) {
		this.storeRoomService = storeRoomService;
	}

	public String[] getNames() {
		return names;
	}

	public void setNames(String[] names) {
		this.names = names;
	}

	public Integer[] getStoreinNums() {
		return storeinNums;
	}

	public void setStoreinNums(Integer[] storeinNums) {
		this.storeinNums = storeinNums;
	}

	public PurchaseService getPurchaseService() {
		return purchaseService;
	}

	public void setPurchaseService(PurchaseService purchaseService) {
		this.purchaseService = purchaseService;
	}

	public Integer[] getDetailid() {
		return detailid;
	}

	public void setDetailid(Integer[] detailid) {
		this.detailid = detailid;
	}

	public Integer[] getDetailstoreNum() {
		return detailstoreNum;
	}

	public void setDetailstoreNum(Integer[] detailstoreNum) {
		this.detailstoreNum = detailstoreNum;
	}

	public Collection<StoreInDetail> getSlist() {
		return slist;
	}

	public void setSlist(Collection<StoreInDetail> slist) {
		this.slist = slist;
	}

	public String getOrderOrproduct() {
		return orderOrproduct;
	}

	public void setOrderOrproduct(String orderOrproduct) {
		this.orderOrproduct = orderOrproduct;
	}

	public Product[] getProducts() {
		return products;
	}

	public void setProducts(Product[] products) {
		this.products = products;
	}

	public ProductStoreService getProductstoreService() {
		return productstoreService;
	}

	public void setProductstoreService(ProductStoreService productstoreService) {
		this.productstoreService = productstoreService;
	}

	public List<String> getMapValidateStockAlert() {
		return mapValidateStockAlert;
	}

	public void setMapValidateStockAlert(List<String> mapValidateStockAlert) {
		this.mapValidateStockAlert = mapValidateStockAlert;
	}

	public Map<String, Double> getMapValidateInMap() {
		return mapValidateInMap;
	}

	public void setMapValidateInMap(Map<String, Double> mapValidateInMap) {
		this.mapValidateInMap = mapValidateInMap;
	}

	public StockAlertService getStockAlertService() {
		return stockAlertService;
	}

	public void setStockAlertService(StockAlertService stockAlertService) {
		this.stockAlertService = stockAlertService;
	}

	public StoreRoom getStoreRoom() {
		return storeRoom;
	}

	public void setStoreRoom(StoreRoom storeRoom) {
		this.storeRoom = storeRoom;
	}

	public String[] getProducts1() {
		return products1;
	}

	public void setProducts1(String[] products1) {
		this.products1 = products1;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public Product[] getProducts(String[] is) {
		if (products == null) {
			return null;
		} else {
			Product[] productst = new Product[is[0].split(" ,").length];

			try {

				String[] productids = is[0].split(" ,");
				String tt = is[0].split(" ,")[is[0].split(" ,").length - 1];
				tt = tt.substring(0, tt.length() - 1);
				for (int i = 0; i < productids.length - 1; i++) {
					productst[i] = this.getProductService().get(
							Integer.parseInt(productids[i]));
				}
				productst[is[0].split(" ,").length - 1] = this
						.getProductService().get(Integer.parseInt(tt));
			} catch (Exception e) {
				e.printStackTrace();
			}
			return productst;
		}
	}

	public double[] getNumbers(String[] is) {
		if (products == null) {
			return null;
		} else {
			double[] integers1 = new double[is[0].split(" ,").length];
			try {
				String[] strings = is[0].split(" ,");
				String tt = is[0].split(" ,")[is[0].split(" ,").length - 1];
				tt = tt.substring(0, tt.length() - 1);
				for (int i = 0; i < strings.length - 1; i++) {
					integers1[i] = Double.valueOf(strings[i]);
				}
				integers1[is[0].split(" ,").length - 1] = Double.valueOf(tt);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return integers1;
		}
	}

	public String[] getStorenumsStrings() {
		return storenumsStrings;
	}

	public void setStorenumsStrings(String[] storenumsStrings) {
		this.storenumsStrings = storenumsStrings;
	}

	public List<Product> getProductlist() {
		return productlist;
	}

	public void setProductlist(List<Product> productlist) {
		this.productlist = productlist;
	}

	public PurchaseOrderDetailService getPurchaseOrderDetailService() {
		return purchaseOrderDetailService;
	}

	public void setPurchaseOrderDetailService(
			PurchaseOrderDetailService purchaseOrderDetailService) {
		this.purchaseOrderDetailService = purchaseOrderDetailService;
	}

	public PurchaseOrderService getPurchaseOrderService() {
		return purchaseOrderService;
	}

	public void setPurchaseOrderService(
			PurchaseOrderService purchaseOrderService) {
		this.purchaseOrderService = purchaseOrderService;
	}

	public CodeInvoiceService getCodeInvoiceService() {
		return codeInvoiceService;
	}

	public void setCodeInvoiceService(CodeInvoiceService codeInvoiceService) {
		this.codeInvoiceService = codeInvoiceService;
	}

	public Collection<CodeInvoice> getCodelist() {
		return codelist;
	}
    
	

	public String[] getIsorder() {
		return isorder;
	}

	public void setIsorder(String[] isorder) {
		this.isorder = isorder;
	}

	public void setCodelist(Collection<CodeInvoice> codelist) {
		this.codelist = codelist;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public CodeInvoice getCodeInvoice() {
		return codeInvoice;
	}

	public void setCodeInvoice(CodeInvoice codeInvoice) {
		this.codeInvoice = codeInvoice;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public String getFlow() {
		return flow;
	}

	public void setFlow(String flow) {
		this.flow = flow;
	}

}
